package com.husd.framework.autocode;

import com.husd.framework.autocode.dto.ClassDefine;
import com.husd.framework.autocode.dto.ClassFieldDefine;
import com.husd.framework.ddl.AutoCodeUtil;
import org.apache.commons.collections4.CollectionUtils;
import org.apache.commons.lang3.StringUtils;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @author shengdonghu@126.com
 * @date 2023/4/24 10:47
 */
public class Ebay04ClassFileConvert {

    private final String sep = "\n";

    public String generateFileContent(ClassDefine root, Map<String, ClassDefine> map) {

        StringBuilder sb = new StringBuilder();

        // 先写注解
        List<String> annotationList = root.getAnnotationList();
        if(CollectionUtils.isNotEmpty(annotationList)) {
            for (String annotation : annotationList) {
                append(sb, annotation);
            }
        }


        // 类 public abstract class OpenSdkEbayXmlPageRes extends OpenSdkEbayXmlBaseRes {
        String t1 = "public class %s extends %s {";
        String t2 = "public class %s {";
        boolean hasParent = StringUtils.isNoneBlank(root.getParentClassName());
        append(sb, hasParent ?
                String.format(t1, root.getClassName(), root.getParentClassName()) :
                String.format(t2, root.getClassName()));

        // 写每一个属性 private Integer totalPage;
        List<ClassFieldDefine> fieldList = root.getFieldList();
        String t3 = " private %s %s;";
        for (ClassFieldDefine classFieldDefine : fieldList) {

            append(sb, classFieldDefine.getFieldAnnotation());
            append(sb, String.format(t3, classFieldDefine.getFieldType(), classFieldDefine.getFieldName()));
            // 复合类型和基本类型的处理不同
            boolean complexType = classFieldDefine.isComplex();
            if (complexType) {
                // 复合类型要把该类型对应的类的声明写在下面 fieldType有可能是一个List
                // 导致map匹配不到 所以需要解析出实际的类型
                String fieldType = classFieldDefine.getFieldType();
                fieldType = AutoCodeUtil.findArrayType(fieldType);
                ClassDefine subroot = map.get(fieldType);
                append(sb, generateFileContent(subroot, map));
            } else {
            }
        }

        append(sb, "}");

        return sb.toString();
    }

    public Map<String, ClassDefine> convert2Map(List<ClassDefine> classDefinesList) {

        Map<String, ClassDefine> map = new HashMap<>();
        for (ClassDefine classDefine : classDefinesList) {

            String key = classDefine.getClassName();
            map.put(key, classDefine);
        }
        return map;
    }

    private void append(StringBuilder sb, String str) {

        sb.append(str).append(sep);
    }
}
